const express = require('express');
const cors = require('cors');
const helmet = require('helmet');
const XianyuApis = require('./services/XianyuApis');
const XianyuWebSocket = require('./services/XianyuWebSocket');

class XianyuServer {
    constructor() {
        this.app = express();
        this.port = process.env.PORT || 3000;
        this.xianyuApis = new XianyuApis();
        this.activeConnections = new Map();
        
        this.setupMiddleware();
        this.setupRoutes();
    }

    /**
     * 设置中间件
     */
    setupMiddleware() {
        // 安全中间件
        this.app.use(helmet());
        
        // CORS中间件
        this.app.use(cors());
        
        // JSON解析中间件
        this.app.use(express.json());
        
        // URL编码解析中间件
        this.app.use(express.urlencoded({ extended: true }));
        
        // 日志中间件
        this.app.use((req, res, next) => {
            console.log(`${new Date().toISOString()} - ${req.method} ${req.path}`);
            next();
        });
    }

    /**
     * 设置路由
     */
    setupRoutes() {
        // 健康检查
        this.app.get('/health', (req, res) => {
            res.json({ 
                status: 'ok', 
                timestamp: new Date().toISOString(),
                version: '1.0.0'
            });
        });

        // 获取访问令牌
        this.app.post('/api/token', async (req, res) => {
            try {
                const { cookies, deviceId } = req.body;
                
                if (!cookies || !deviceId) {
                    return res.status(400).json({
                        success: false,
                        error: '缺少必要参数: cookies 和 deviceId'
                    });
                }

                const tokenResponse = await this.xianyuApis.getToken(cookies, deviceId);
                res.json({
                    success: true,
                    data: tokenResponse
                });
                
            } catch (error) {
                console.error('获取令牌失败:', error.message);
                res.status(500).json({
                    success: false,
                    error: error.message
                });
            }
        });

        // 发送API请求
        this.app.post('/api/request', async (req, res) => {
            try {
                const { endpoint, data, cookies, options } = req.body;
                
                if (!endpoint || !data || !cookies) {
                    return res.status(400).json({
                        success: false,
                        error: '缺少必要参数: endpoint, data 和 cookies'
                    });
                }

                const response = await this.xianyuApis.makeRequest(endpoint, data, cookies, options);
                res.json({
                    success: true,
                    data: response
                });
                
            } catch (error) {
                console.error('API请求失败:', error.message);
                res.status(500).json({
                    success: false,
                    error: error.message
                });
            }
        });

        // 建立WebSocket连接
        this.app.post('/api/websocket/connect', async (req, res) => {
            try {
                const { cookies, connectionId } = req.body;
                
                if (!cookies) {
                    return res.status(400).json({
                        success: false,
                        error: '缺少必要参数: cookies'
                    });
                }

                const connectionIdFinal = connectionId || `conn_${Date.now()}`;
                
                // 创建WebSocket连接
                const wsConnection = new XianyuWebSocket(cookies, this.xianyuApis);
                await wsConnection.connect();
                
                // 存储连接
                this.activeConnections.set(connectionIdFinal, wsConnection);
                
                res.json({
                    success: true,
                    connectionId: connectionIdFinal,
                    message: 'WebSocket连接已建立'
                });
                
            } catch (error) {
                console.error('WebSocket连接失败:', error.message);
                res.status(500).json({
                    success: false,
                    error: error.message
                });
            }
        });

        // 发送WebSocket消息
        this.app.post('/api/websocket/send', async (req, res) => {
            try {
                const { connectionId, message } = req.body;
                
                if (!connectionId || !message) {
                    return res.status(400).json({
                        success: false,
                        error: '缺少必要参数: connectionId 和 message'
                    });
                }

                const connection = this.activeConnections.get(connectionId);
                if (!connection) {
                    return res.status(404).json({
                        success: false,
                        error: '连接不存在'
                    });
                }

                await connection.sendMessage(message);
                res.json({
                    success: true,
                    message: '消息发送成功'
                });
                
            } catch (error) {
                console.error('发送消息失败:', error.message);
                res.status(500).json({
                    success: false,
                    error: error.message
                });
            }
        });

        // 关闭WebSocket连接
        this.app.delete('/api/websocket/connect/:connectionId', (req, res) => {
            try {
                const { connectionId } = req.params;
                const connection = this.activeConnections.get(connectionId);
                
                if (!connection) {
                    return res.status(404).json({
                        success: false,
                        error: '连接不存在'
                    });
                }

                connection.close();
                this.activeConnections.delete(connectionId);
                
                res.json({
                    success: true,
                    message: '连接已关闭'
                });
                
            } catch (error) {
                console.error('关闭连接失败:', error.message);
                res.status(500).json({
                    success: false,
                    error: error.message
                });
            }
        });

        // 获取活跃连接列表
        this.app.get('/api/websocket/connections', (req, res) => {
            const connections = Array.from(this.activeConnections.keys());
            res.json({
                success: true,
                data: {
                    count: connections.length,
                    connections: connections
                }
            });
        });

        // 404处理
        this.app.use('*', (req, res) => {
            res.status(404).json({
                success: false,
                error: '接口不存在'
            });
        });

        // 错误处理中间件
        this.app.use((error, req, res, next) => {
            console.error('服务器错误:', error);
            res.status(500).json({
                success: false,
                error: '服务器内部错误'
            });
        });
    }

    /**
     * 启动服务器
     */
    start() {
        this.app.listen(this.port, () => {
            console.log(`🚀 闲鱼API服务器已启动`);
            console.log(`📍 服务地址: http://localhost:${this.port}`);
            console.log(`📊 健康检查: http://localhost:${this.port}/health`);
            console.log(`⏰ 启动时间: ${new Date().toISOString()}`);
        });
    }

    /**
     * 优雅关闭服务器
     */
    async shutdown() {
        console.log('正在关闭服务器...');
        
        // 关闭所有WebSocket连接
        for (const [id, connection] of this.activeConnections) {
            connection.close();
        }
        this.activeConnections.clear();
        
        console.log('服务器已关闭');
        process.exit(0);
    }
}

module.exports = XianyuServer;
